<template>
  <div class="payment-page">
    <div class="payment-container">
      <!-- 顶部标题栏 -->
      <div class="payment-header">
        <div class="payment-title">
          正在使用即时到账交易 [?]
        </div>
        <div class="payment-info">
          <span class="order-text">订单号：{{ orderInfo.orderNo }}</span>
          <span class="payment-amount">{{ orderInfo.amount }}</span>
          <span class="currency">元</span>
        </div>
      </div>

      <!-- 支付内容区 -->
      <div class="payment-content">
        <!-- 左侧扫码支付 -->
        <div class="qrcode-section">
          <h3>扫码支付</h3>
          <div class="qrcode-container">
            <img :src="qrCodeUrl" alt="支付二维码" v-if="qrCodeUrl">
            <div class="qrcode-loading" v-else>
              <el-spinner></el-spinner>
              <span>正在生成支付二维码...</span>
            </div>
          </div>
          <div class="qrcode-tips">
            <p>使用手机支付宝扫码完成付款</p>
            <div class="payment-timer" v-if="countdownTime">
              支付倒计时：{{ countdownTime }}
            </div>
            <div class="download-links">
              <a href="#">手机支付宝下载</a> | <a href="#">如何使用？</a>
            </div>
          </div>
        </div>

        <!-- 右侧登录区域 -->
        <div class="login-section">
          <h3>登录支付宝账户付款</h3>
          <div class="login-form">
            <div class="form-item">
              <label>账户名：</label>
              <el-input v-model="loginForm.username" placeholder="手机号码/邮箱"></el-input>
              <a href="#" class="forgot-link">忘记账户名？</a>
            </div>
            <div class="form-item">
              <label>支付密码：</label>
              <el-input v-model="loginForm.password" type="password" placeholder="请输入支付密码"></el-input>
              <a href="#" class="forgot-link">忘记密码？</a>
            </div>
            <div class="form-actions">
              <el-button type="primary" class="next-btn">下一步</el-button>
            </div>
          </div>
          <div class="register-link">
            <a href="#">新用户注册</a>
          </div>
        </div>
      </div>

      <!-- 底部说明 -->
      <div class="payment-footer">
        <p>安全设置检测：支付宝为你提供账户资金安全保障服务。</p>
      </div>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode'

export default {
  name: 'PaymentPage',
  data() {
    return {
      qrCodeUrl: '',
      orderInfo: {
        orderNo: '',
        amount: 0,
        subject: ''
      },
      loginForm: {
        username: '',
        password: ''
      },
      paymentTimer: null,
      statusCheckTimer: null,
      countdownTime: ''
    }
  },
  created() {
    // 从路由参数获取订单信息
    const { orderNo, amount, subject } = this.$route.query
    console.log('获取到的订单参数:', { orderNo, amount, subject });
    
    if (!orderNo || !amount) {
      this.$message.error('订单信息不完整');
      this.$router.push('/orders');
      return;
    }
    
    this.orderInfo = {
      orderNo,
      amount,
      subject: subject || '达尔优61蓝牙机械键盘'
    }
    this.createQrCode()
  },
  beforeDestroy() {
    this.clearTimers()
  },
  methods: {
    async createQrCode() {
      try {
        console.log('开始创建支付二维码...');
        // 构建支付参数
        const payParams = {
          orderId: this.orderInfo.orderNo,
          amount: this.orderInfo.amount,
          subject: "鲜花订单-" + this.orderInfo.orderNo
        };
        console.log('支付参数:', payParams);

        console.log('准备发送请求到:', '/alipay/createQrCode');
        const response = await this.request.post('/alipay/createQrCode', payParams);
        console.log('支付二维码接口响应:', response);

        if (response && response.data && response.data.qrCode) {
          // 生成二维码图片
          this.qrCodeUrl = await QRCode.toDataURL(response.data.qrCode);
          console.log('二维码生成成功');
          // 开始检查支付状态
          this.startCheckPaymentStatus();
        } else {
          console.error('响应数据格式不正确:', response);
          this.$message.error('创建支付二维码失败');
        }
      } catch (error) {
        console.error('创建支付二维码失败:', error);
        console.error('错误详情:', error.response || error);
        this.$message.error('创建支付二维码失败，请重试');
      }
    },

    startCheckPaymentStatus() {
      // 清除可能存在的旧定时器
      this.clearTimers();
      
      // 设置支付倒计时
      let timeLeft = 5 * 60; // 5分钟
      this.paymentTimer = setInterval(() => {
        timeLeft--;
        const minutes = Math.floor(timeLeft / 60);
        const seconds = timeLeft % 60;
        this.countdownTime = `${minutes}:${seconds.toString().padStart(2, '0')}`;
        
        if (timeLeft <= 0) {
          this.clearTimers();
          this.$message.warning('支付超时，请重新发起支付');
          // 返回订单列表页
          this.$router.push('/orders');
        }
      }, 1000);

      // 设置状态检查定时器
      this.statusCheckTimer = setInterval(async () => {
        try {
          const response = await this.request.get('/alipay/checkStatus', {
            orderNo: this.orderInfo.orderNo
          });

          if (response.data === true) {
            this.clearTimers();
            this.$message.success('支付成功！');
            // 清除结算信息
            localStorage.removeItem('checkoutInfo');
            // 直接跳转到首页
            this.$router.push('/');
          }
        } catch (error) {
          console.error('检查支付状态失败:', error);
        }
      }, 3000); // 每3秒检查一次
    },

    clearTimers() {
      if (this.paymentTimer) {
        clearInterval(this.paymentTimer);
        this.paymentTimer = null;
      }
      if (this.statusCheckTimer) {
        clearInterval(this.statusCheckTimer);
        this.statusCheckTimer = null;
      }
    }
  }
}
</script>

<style scoped>
.payment-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.payment-container {
  max-width: 1000px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.payment-header {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
}

.payment-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.payment-info {
  font-size: 14px;
  color: #333;
}

.order-text {
  margin-right: 20px;
}

.payment-amount {
  color: #ff4d4f;
  font-size: 20px;
  font-weight: bold;
  margin: 0 5px;
}

.currency {
  color: #ff4d4f;
}

.payment-content {
  display: flex;
  padding: 30px;
  border-bottom: 1px solid #e8e8e8;
}

.qrcode-section {
  flex: 1;
  padding-right: 30px;
  border-right: 1px solid #e8e8e8;
}

.qrcode-section h3,
.login-section h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 20px;
  font-weight: normal;
}

.qrcode-container {
  width: 200px;
  height: 200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e8e8e8;
  padding: 10px;
}

.qrcode-container img {
  width: 100%;
  height: 100%;
}

.qrcode-tips {
  text-align: center;
  margin-top: 20px;
}

.qrcode-tips p {
  color: #666;
  margin-bottom: 10px;
}

.download-links {
  font-size: 12px;
}

.download-links a {
  color: #1890ff;
  text-decoration: none;
}

.login-section {
  flex: 1;
  padding-left: 30px;
}

.form-item {
  margin-bottom: 20px;
  position: relative;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  color: #666;
}

.forgot-link {
  position: absolute;
  right: 0;
  top: 0;
  color: #1890ff;
  text-decoration: none;
  font-size: 12px;
}

.form-actions {
  margin-top: 30px;
}

.next-btn {
  width: 100%;
  height: 40px;
}

.register-link {
  text-align: right;
  margin-top: 15px;
}

.register-link a {
  color: #1890ff;
  text-decoration: none;
  font-size: 12px;
}

.payment-footer {
  padding: 20px;
  color: #999;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .payment-content {
    flex-direction: column;
  }

  .qrcode-section {
    border-right: none;
    border-bottom: 1px solid #e8e8e8;
    padding-right: 0;
    padding-bottom: 30px;
    margin-bottom: 30px;
  }

  .login-section {
    padding-left: 0;
  }
}

.payment-timer {
  margin: 10px 0;
  color: #ff4d4f;
  font-size: 16px;
  font-weight: bold;
}
</style> 